package com.soulmate.auth.authencation;

import com.soulmate.auth.token.TelephoneCodeAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 手机号验证码认证provider
 * @author huaiping
 */
@Slf4j
@Component
public class TelephoneCodeAuthenticationProvider implements AuthenticationProvider {


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String principal = (String) authentication.getPrincipal();
        String credentials = (String) authentication.getCredentials();
        if (verifyCode(principal, credentials)) {
            // 生成一个userDetail
            UserDetails userDetails = new User(principal, credentials, true,
                    true,true, true,
                    List.of(new SimpleGrantedAuthority("admdin")));
            return new TelephoneCodeAuthenticationToken(userDetails, credentials,
                    List.of(new SimpleGrantedAuthority("admdin")));
        }
        return new TelephoneCodeAuthenticationToken(principal, credentials);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (TelephoneCodeAuthenticationToken.class.isAssignableFrom(authentication));
    }


    /**
     * 验证code
     *
     * @param telephone 电话
     * @param code      code
     * @return boolean
     */
    protected boolean verifyCode(String telephone, String code) {
        return telephone.equals(code);
    }
}
